<template>
    <div class="chatBodyVue flex_column relative">
        <img src="../../../assets/chat.png" style="width: 132px; height: 100px;" class="absolute_auto" v-if="JSON.stringify(currentChat)=='{}'">
        <template v-else>
            <div class="topVue">
                <div class="title">与{{ currentChat.type===0 ? currentChat.friendWechatName : currentChat.groupName}}的聊天</div>
            </div>
            <div class="content" ref="chatBody" @scroll="handleChatScroll($event)">
                <div class="flex align_center" style="padding: 0 40px;" v-if="isLoading">
                    <el-divider></el-divider>
                    <span class="el-icon-loading" style="padding: 0 15px; font-size: 20px"></span>
                    <el-divider></el-divider>
                </div>
                    <div class="li" v-for="(o, i) in history" :key="i">
                        <template v-if="o.location===1">
                            <div class="location1">
                                <div class="left">
                                    <div class="name">{{o.userWechatName}}</div>
                                    <div class="messagevue" v-if="o.messageType===0 || o.messageType==null" v-html="o.message.replace(/\n/g, '<br>')"></div>
                                    <viewer :toolbar="false" v-if="o.messageType===1" style="margin-top: 10px">
                                        <img :src="o.message" style="max-width: 200px; min-width: 10px; height: auto; margin-top: 10px; cursor: pointer;">
                                    </viewer>
                                    <div class="messagevue" v-if="o.messageType===2" style="cursor: pointer;" @click="onPlay(o.message)">
                                        <img src="../../../assets/voice2.png" style="width: 20px; height: 20px;">
                                    </div>
                                    <div class="messagevue flex align_center" v-if="o.messageType>=3" style="cursor: pointer" @click="fileDownload(o.message)">
                                        <img src="../../../assets/file_white.png" style="width: 20px; height: 20px">
                                        <span style="color: #fff; font-weight: 400; padding-left: 10px">{{ splitilter(o.message) }}</span>
                                    </div>
                                </div> 
                                <img src="../../../assets/AI.png" style="width: 50px; height: 50px;">
                            </div>
                        </template>
                        <template v-if="o.location===0">
                            <div class="location0 flex">
                                <img src="../../../assets/user.png" style="width: 50px; height: 50px;">
                                <div class="right">
                                    <div class="name">{{o.senderWechatName}}</div>
                                    <div class="messagevue" v-if="o.messageType===0 || o.messageType==null" v-html="o.message.replace(/\n/g, '<br>')"></div>
                                    <viewer :toolbar="false" v-if="o.messageType===1" style="margin-top: 10px">
                                        <img :src="o.message" style="max-width: 200px; min-width: 10px; height: auto; margin-top: 10px; cursor: pointer;">
                                    </viewer>
                                   
                                    <div class="messagevue" v-if="o.messageType===2" style="cursor: pointer;" @click="onPlay(o.message)">
                                        <img src="../../../assets/voice1.png" style="width: 20px; height: 20px;">
                                    </div>
                                    <div class="messagevue flex align_center" v-if="o.messageType>=3" style="cursor: pointer" @click="fileDownload(o.message)">
                                        <img src="../../../assets/file_black.png" style="width: 20px; height: 20px">
                                        <span style="color: #333; font-weight: 400; padding-left: 10px">{{ splitilter(o.message) }}</span>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                <div class="hasNew"></div>
            </div>
            <div class="sendVue">
                <textarea v-model="message" :placeholder="currentChat.type===0 ? `发送给好友${currentChat.friendWechatName}` : `发送到群聊${currentChat.groupName}`" @keydown.enter.prevent="handleSend" :maxlength="2000"></textarea>
                <div class="botVue flex_between align_center">
                    <div style="width: 32px; height: 32px; position: relative;">
                        <input ref="clearRef" class="fileBtn" type="file" id="fileupload" accept="image/*" @change="fileChange($event)"/>
                        <img src="../../../assets/file.png" title="发送图片" style="width: 32px; height: 32px; cursor: pointer;">
                    </div>
                    <img src="../../../assets/send.png" style="width: 32px; height: 32px; cursor: pointer;" title="发送" @click="sendFun">
                </div>
            </div>
        </template>

        <vView :src="src" :dialogTableVisible="dialogTableVisible" @beforeClose="dialogTableVisible=false"></vView>
    </div>
</template>

<script>
import { mapState } from "vuex"
import { post } from "@/common/request.js"
import vView from '@/components/vView.vue'
import { toast } from "@/common/tools"
export default {
    components: {
        vView
    },
    data(){
        return {
            pageNum: 1,
            pageSize: 30,
            isLoading: false,
            isLastPage: false,
            message: "",
            isSend: false,
            src: "",
            dialogTableVisible: false
        }
    },
    computed: {
        ...mapState({
            currentChat: state=> state.currentChat,
            user: state=> state.user,
            history: state=> state.history,
            currentWeChat: state=> state.currentWeChat,
            toBottomRandom: state=> state.toBottomRandom
        })
    },
    watch: {
        toBottomRandom(){
            setTimeout(() => {
                this.scrollToBottom()
            }, 200);
        }
    },
    methods: {
        // 获取某个好友或者群聊的聊天记录
        getHistory(data){
            if(data) this.pageNum = 1
            this.$post("/front/weChatMsg/friendMessageList", {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                friendId: this.currentChat.id
            }).then(res=>{
                if(res.data.code===0) {
                    this.$store.state.history = res.data.obj.list
                    this.isLastPage = res.data.obj.isLastPage
                    setTimeout(() => {
                        this.scrollToBottom()
                    }, 200);
                }
            })
        },

        toView(src){
            this.src = src
            this.dialogTableVisible = true
        },

        // 滑动到聊天最底部
        scrollToBottom(){
            this.$nextTick(()=>{
                let dom = this.$refs.chatBody
                console.log(dom)
                dom.scrollTo({ top: dom.scrollHeight, behavior: 'auto' });
            })
        },

        // 聊天记录分页加载
        handleChatScroll(e){
            let scrollTop = e.target.scrollTop
            if(this.isLastPage || this.isLoading || scrollTop>0) return
            this.pageNum ++
            this.isLoading = true
            this.$post("/front/weChatMsg/friendMessageList", {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                friendId: this.currentChat.id
            }).then(res=>{
                if(res.data.code===0) {
                        let history = res.data.obj.list
                        this.isLastPage = res.data.obj.isLastPage
                        this.isLoading = false
                        let chatDom = this.$refs.chatBody
                        let currentHeight = chatDom.scrollHeight
                    for(let i=0; i<history.length; i++){
                        this.$store.state.history.unshift(history[i])
                        if(i===history.length-1) {
                            this.$nextTick(()=>{
                                chatDom.scrollTop = chatDom.scrollHeight - currentHeight
                            })
                        }
                    }     
                }
            }) 
        },

        isAllSpaces(str) {
            return /^\s+$/.test(str);
        },

        handleSend(event){
            console.log(event)
            event.preventDefault(); // 阻止默认的换行行为
            this.sendFun()
        },

        fileDownload(url){
            window.open(url)
        },

        // 播放语音
        onPlay(url){
            let audio = document.getElementById("audio");
            audio.src = url
            audio.play()
        },
        
        // 发送消息
        sendFun(){
            console.log(this.currentChat, this.isSend)
            if(!this.message) return toast(1, "发送消息内容不能为空")
            if(this.isAllSpaces(this.message)) return toast(1, "发送消息为无效内容")
            if(this.currentWeChat.currentOnLineStatus==0) return toast(1, "当前微信已离线，无法发送消息，请登录后尝试")
            if(this.isSend) return
            this.isSend = true
            post("/front/weChatMsg/sendTextMsg", {
                friendId: this.currentChat.id,
                friendWechatId: this.currentChat.friendWechatId,
                friendWechatName: this.currentChat.friendWechatName,
                friendWechatRemark: this.currentChat.friendWechatRemark,
                groupId: this.currentChat.type===1 ? this.currentChat.groupId : "",
                groupName: "",
                userWechatName: this.currentChat.userWechatName,
                userWechatId: this.currentChat.userWechatId,
                port: this.currentChat.port,
                message: this.message
            }).then(res=>{
                if(res.data.code===0) {
                    this.isSend = false
                    this.message = ""
                    let messageObj = res.data.obj
                    messageObj.message = res.data.obj.lastMessage
                    messageObj.messageType = res.data.obj.lastMessageType,
                    this.$store.state.history.push(messageObj)
                    this.$store.state.chatting = this.$store.state.chatting.filter(o=>{
                        return o.id != messageObj.id
                    })
                    this.$store.state.chatting.unshift(messageObj)

                    setTimeout(() => {
                        this.scrollToBottom()
                    }, 200);
                }else{
                    toast(1, res.data.msg)
                    this.isSend = false
                }
            })
        },

        // 发送图片
        fileChange(event){
            if(this.currentWeChat.cucurrentOnLineStatus==0) return toast(1, "当前微信已离线，无法发送消息，请登录后尝试")
            let file = event.target.files[0];
            let formData = new FormData()
            formData.append("file", file)
            post("/front/search/uploadImage", formData).then(res=>{
                this.pageNum = 1
                post("/front/weChatMsg/sendImageMsg", {
                    friendId: this.currentChat.id,
                    friendWechatId: this.currentChat.friendWechatId,
                    friendWechatName: this.currentChat.friendWechatName,
                    friendWechatRemark: this.currentChat.friendWechatRemark,
                    groupId: this.currentChat.type===1 ? this.currentChat.groupId : "",
                    groupName: "",
                    userWechatName: this.currentChat.userWechatName,
                    userWechatId: this.currentChat.userWechatId,
                    port: this.currentChat.port,
                    message: res.data.obj
                }).then(result=>{
                    if(result.data.code===0) {
                        if(this.$refs.clearRef.value) this.$refs.clearRef.value = ''; // 清空file文件
                        setTimeout(() => {
                            this.getHistory()
                        }, 200);
                    }else{
                        if(this.$refs.clearRef.value) this.$refs.clearRef.value = ''; // 清空file文件
                        toast(1, res.data.msg)
                    }
                })
            })
        },

        splitilter(value){
            let array = value.split("/")
            return array[array.length-1]
        },
    }
}
</script>


<style lang="less" scoped>
.chatBodyVue {
    width: 100%;
    height: 100%;
    .topVue {
        width: 100%;
        height: 60px;
        border-bottom: 1px solid #f5f5f5;
        .title {
            width: 100%;
            height: 60px;
            line-height: 60px;
            text-align: center;
            font-weight: 600;
            color: #333;
            font-weight: 600;
        }
    }
    .content {
        width: 100%;
        flex: 1;
        overflow-y: scroll;
        padding: 0 10px;
        .li {
            width: 100%;
            padding: 10px 0;
            .location1 {
                display: flex;
                justify-content: end;
                .left {
                    padding-right: 10px;
                    display: flex;
                    justify-content: end;
                    align-items: end;
                    flex-direction: column;
                    max-width: 60%;
                    .name {
                        color: #999;
                        font-weight: 600;
                        font-size: 14px;
                    }
                    .messagevue {
                        background: #0147fd;
                        border-radius: 5px;
                        color: #fff;
                        line-height: 1.4;
                        padding: 10px;
                        margin-top: 10px;
                        word-break: break-all;
                        white-space: wrap;
                    }
                }
            }
            .location0 {
                .right {
                    padding-left: 10px;
                    max-width: 60%;
                    .name {
                            color: #999;
                            font-size: 14px;
                            font-weight: 600;
                    }
                    .messagevue {
                        background: #f5f5f5;
                        border-radius: 5px;
                        color: #333;
                        line-height: 1.4;
                        padding: 10px;
                        margin-top: 10px;
                        word-break: break-all;
                        white-space: wrap;
                    }
                 }
            }   
                
        }
    }
    .content::-webkit-scrollbar {
        width: 0;
        height: 0;
    }
    .sendVue {
        width: 100%;
        height: 150px;
        border-top: 1px solid #f5f5f5;
        margin-top: 10px;
        textarea {
            width: 100%;
            height: 90px;
            display: block;
            box-sizing: border-box;
            resize: none;
            border-radius: 4px;
            font-family: PingFangSC, PingFang SC;
            padding: 10px;
            font-size: 14px;
        }
        ::-webkit-input-placeholder { /* WebKit browsers */
            color: #AAA;
            font-size: 14px;
            font-family: PingFangSC, PingFang SC;
        }
        :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
            color: #AAA;
            font-size: 14px;
            font-family: PingFangSC, PingFang SC;
        }
        ::-moz-placeholder { /* Mozilla Firefox 19+ */
            color: #AAA;
            font-size: 14px;
            font-family: PingFangSC, PingFang SC;
        }
        :-ms-input-placeholder { /* Internet Explorer 10+ */
            color: #AAA;
            font-size: 14px;
            font-family: PingFangSC, PingFang SC;
        }
    }
    .botVue {
        width: 100%;
        height: 60px;
        padding: 0 15px;
        .fileBtn {
            width: 32px;
            height: 32px;
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
            z-index: 9998;
            border: none;
            outline: none;
        }
    }
}
</style>